package site.shihuan.helpdesk.im.message.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import site.shihuan.helpdesk.im.message.BaseMessage;

/**
 * 聊天消息
 *
 * @author 周世焕
 * @Date 2021/2/2 20:08
 */
@Slf4j
@Data
public class ChatMessage extends BaseMessage {

    private String sender;

    private String receiver;

    private long date;

    private String type;

    private String msg;

    private String tenantId;

    private String contactId;

    public ChatMessage() {
        super(TYPE_CHAT);
    }

    @Override
    public void decode(String content) {
        JSONArray jsonArray = JSONUtil.parseArray(content);
        String[] params = new String[4];
        params = jsonArray.toArray(params);
        log.debug("message params: {}", ArrayUtils.toString(params));
        type = params[0];
        contactId = params[1];
        receiver = params[2];
        msg = params[3];
        date = System.currentTimeMillis();
    }

    @Override
    public String encode() {
        JSONObject result = new JSONObject();
        result.set(PROPERTY_TYPE,TYPE_CHAT);
        JSONArray content = new JSONArray();
        content.add(type);
        content.add(sender);
        content.add(msg);
        content.add(date);
        result.set(PROPERTY_CONTENT,content);
        return result.toStringPretty();
    }

    @Override
    public String toString() {
        return "ChatMessage{" +
                "sender='" + sender + '\'' +
                ", receiver='" + receiver + '\'' +
                ", date=" + date +
                ", type='" + type + '\'' +
                ", msg='" + msg + '\'' +
                '}';
    }
}
